package com.example.contactapp;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;

public class ContactAdapter extends BaseAdapter {
    private List<Contact> contacts;
    private Context context;
    private TextView stickyHeader;

    public ContactAdapter(List<Contact> contacts, Context context, TextView stickyHeader) {
        this.contacts = contacts;
        this.context = context;
        this.stickyHeader = stickyHeader;
    }

    @Override
    public int getCount() {
        return contacts.size();
    }

    @Override
    public Object getItem(int position) {
        return contacts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_contact, parent, false);
        }

        Contact contact = contacts.get(position);
        TextView nameTextView = convertView.findViewById(R.id.text_view_name);

        TextView phoneTextView = convertView.findViewById(R.id.text_view_phone);

        nameTextView.setText(contact.getName());
        phoneTextView.setText(contact.getPhone());

        return convertView;
    }

    public void updateStickyHeader(int position) {
        if (position >= 0 && position < contacts.size()) {
            char currentFirstLetter = contacts.get(position).getFirstLetter();
            if (stickyHeader != null) { // 确保 stickyHeader 不为 null
                stickyHeader.setText(String.valueOf(currentFirstLetter));
                stickyHeader.setVisibility(View.VISIBLE);
            }
        } else {
            if (stickyHeader != null) { // 确保 stickyHeader 不为 null
                stickyHeader.setVisibility(View.GONE);
            }
        }
    }
}